#include "delay.h"
volatile uint32_t usTicks        = 0;
volatile uint32_t System_Time_ms = 0;

void SysTick_IntHandler(void)
{
	 System_Time_ms++;
}

void delay_init(void)
{
	SysTickPeriodSet(SystemCoreClock/1000);    // 1ms
	SysTickIntRegister(SysTick_IntHandler);
	SysTickIntEnable();
	SysTickEnable();
	usTicks = SystemCoreClock / 1000000;       // usTicks = 120
}
uint32_t micros(void)
{
	register uint32_t ms, tick;     
	do{
			ms   = System_Time_ms;
			tick = HWREG(NVIC_ST_CURRENT); 
	}while(ms != System_Time_ms);
	
	return (ms+1)*1000 - tick/usTicks; 
}
void delay_us(uint32_t nus)
{
	uint32_t t0 = micros();
    while(micros() - t0 < nus)
        ;	
}
void delay_ms(uint32_t nms)
{
	uint32_t t0 = micros();
    while(micros() - t0 < nms*1000)
        ;
}





